import { View, Image, Text } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { Tabs } from '@nutui/nutui-react-taro';
import { useState, useEffect, useMemo, useRef } from 'react';
import { InfiniteList } from '@/components';
import type { ActionType } from '@/components/InfiniteList';
import { BasicLayout } from '@/layouts';
import { getApiChoiceOutPersonListCompanyId } from '@/api';
import { FourGreatEnum } from '@/interfaces/fourGreat';
import { RouterUtil, TabbarUtil } from '@/utils';
import { StorageKey } from '@/constants/storage';
import { usePreselectStore } from '@/models';
import { useDidShow } from '@tarojs/taro';
import type { GetApiChoiceOutPersonListCompanyIdResponse } from '@/api';
import { DEFAULT_PAGE_SIZE } from '@/constants';
import styles from './index.module.scss';

// 四大金刚类型列表
const fourGreatTypeList = Object.entries(FourGreatEnum)
  .filter(([key]) => isNaN(Number(key)))
  .map(([key, value]) => ({
    text: key,
    value: value,
  }));

type PersonItem = NonNullable<GetApiChoiceOutPersonListCompanyIdResponse>[0];

const Makeup = () => {
  const router = useRouter();
  const infiniteListRef = useRef<ActionType>(null);
  
  // 从路由参数获取初始类型，默认为化妆师
  const initialType = useMemo(() => {
    const type = router.params?.type;
    return type ? Number(type) : FourGreatEnum.化妆师;
  }, [router.params?.type]);

  const [activeTab, setActiveTab] = useState<number>(initialType);
  const shopId = Taro.getStorageSync(StorageKey.SHOP_ID);
  const { dresses, persons } = usePreselectStore();
  
  // 缓存所有数据，避免重复请求
  const [allDataCache, setAllDataCache] = useState<Record<number, PersonItem[]>>({});

  // 页面显示时更新 tabbar badge
  useDidShow(() => {
    const totalCount = dresses.length + persons.length;
    TabbarUtil.setPreselectBadge(totalCount);
  });

  // 当路由参数变化时，更新activeTab
  useEffect(() => {
    if (router.params?.type) {
      const type = Number(router.params.type);
      if (type !== activeTab) {
        setActiveTab(type);
      }
    }
  }, [router.params?.type]);

  // 处理Tab切换
  const handleTabChange = (value: number) => {
    setActiveTab(value);
    // 切换tab时刷新列表
    infiniteListRef.current?.refresh();
  };

  // 构建请求参数
  const requestParams = useMemo(() => {
    return {
      companyId: shopId,
      type: activeTab,
    };
  }, [shopId, activeTab]);

  // 解析四大金刚的图片
  const getMakeupPictureUrl = (item: PersonItem) => {
    if (!item?.bizData) return '';
    try {
      const bizData = JSON.parse(item.bizData);
      if (bizData?.pictureUrl && Array.isArray(bizData.pictureUrl)) {
        return bizData.pictureUrl[0] || '';
      }
    } catch {
      return '';
    }
    return '';
  };

  // 请求函数包装器（实现前端分页）
  const requestWrapper = async (params: any) => {
    const pageNum = Number(params.pageNum) || 1;
    const pageSize = Number(params.pageSize) || DEFAULT_PAGE_SIZE;
    const currentType = params.type || requestParams.type;
    
    let allData: PersonItem[] = [];
    
    // 如果缓存中有数据，直接使用缓存
    if (allDataCache[currentType]) {
      allData = allDataCache[currentType];
    } else {
      // 如果缓存中没有数据，先获取所有数据
      const response = await getApiChoiceOutPersonListCompanyId({
        companyId: shopId,
        type: currentType,
      });
      allData = response.data || [];
      // 更新缓存
      setAllDataCache(prev => ({
        ...prev,
        [currentType]: allData,
      }));
    }
    
    // 前端分页：计算当前页的数据
    const startIndex = (pageNum - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageData = allData.slice(startIndex, endIndex);
    
    // 将数据转换为行格式（每行两个）
    const formattedData = formatPersonData(pageData);
    
    // 计算行总数：原始总数除以2，向上取整
    const originalTotal = allData.length;
    const rowTotal = Math.ceil(originalTotal / 2);
    
    // 返回符合BaseResponse格式的数据
    return {
      code: '200',
      message: 'success',
      success: true,
      msg: 'success',
      data: {
        data: formattedData,
        current: pageNum,
        pageSize: pageSize,
        total: rowTotal,
      },
    };
  };

  // 将人员列表数据转换为每行两个的格式
  const formatPersonData = (data: PersonItem[]) => {
    const rows: PersonItem[][] = [];
    for (let i = 0; i < data.length; i += 2) {
      const row = [data[i]];
      if (data[i + 1]) {
        row.push(data[i + 1]);
      }
      rows.push(row);
    }
    return rows;
  };

  // 渲染人员行（每一项显示两个人员）
  const renderPersonRow = (rowData: PersonItem[]) => {
    return (
      <View className={styles.personRow}>
        {rowData.map((item, index) => (
          <View key={item?.id || `empty-${index}`} className={styles.personItem}>
            {item ? (
              <View
                className={styles.personCard}
                onClick={() => {
                  RouterUtil.navigateTo('/pages/makeup/detail/index', {
                    id: item.id,
                    type: activeTab,
                  });
                }}
              >
                <View className={styles.personImage}>
                  {getMakeupPictureUrl(item) ? (
                    <Image
                      src={getMakeupPictureUrl(item)}
                      mode="aspectFill"
                      className={styles.image}
                    />
                  ) : (
                    <View className={styles.placeholder}>暂无图片</View>
                  )}
                </View>
                <View className={styles.personInfo}>
                  <Text className={styles.personName}>{item.name || '未知'}</Text>
                </View>
              </View>
            ) : (
              // 空占位符，保持布局一致性
              <View className={styles.emptyPlaceholder} />
            )}
          </View>
        ))}
      </View>
    );
  };

  return (
    <BasicLayout 
      title="化妆摄影"
      className={styles.page}
      fill
      safeArea={false}
    >
      <View className={styles.makeupPage}>
        {/* Tabs */}
        <View className={styles.tabsSection}>
          <Tabs
            value={activeTab}
            onChange={handleTabChange}
            direction="horizontal"
          >
            {fourGreatTypeList.map((type) => (
              <Tabs.TabPane key={type.value} title={type.text} value={type.value} />
            ))}
          </Tabs>
        </View>

        {/* 人员列表 */}
        <InfiniteList
          className={styles.personListContainer}
          params={requestParams}
          request={requestWrapper}
          renderItem={renderPersonRow}
          actionRef={infiniteListRef}
          refresherEnabled
          padding
        />
      </View>
    </BasicLayout>
  );
};

export default Makeup;
